package com.chixing.interceptor;

import com.chixing.annotation.AutoIdempotent;
import com.chixing.service.IdempotentTokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 幂等性拦截器
 */

@Component
public class AutoIdempotentInterceptor implements HandlerInterceptor {
    @Autowired
    private IdempotentTokenService idempotentTokenService;
    //preHandle：在调用controller 方法之前 拦截
    // 拦截controller 中方法上 是否有  @AutoIdempotent ， 若有，就 进行 验证幂等性checkToken()
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("正在执行拦截器AutoIdempotentInterceptor 。。。。。。。 ");

        String token =  request.getHeader("formToken");
        System.out.println("拦截器中获得的formToken：" + token);

        if(!(handler instanceof HandlerMethod)) return  true;
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        AutoIdempotent annotation = handlerMethod.getMethod().getAnnotation(AutoIdempotent.class);
        if(annotation !=null){
            return idempotentTokenService.checkToken(token);
        }
        return true;  // 放行
    }
}
